package com.hncc.kumao.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hncc.kumao.exception.KumaoException;
import com.hncc.kumao.util.ConstValue;
import com.hncc.kumao.util.JWTUtils;
import com.hncc.kumao.util.JedisUtils;
import com.opensymphony.xwork2.ActionSupport;

import redis.clients.jedis.Jedis;

public class BaseAction extends ActionSupport {

    //返回json格式数据
    public void jsonReturn(boolean success, int code, Object value) {
       Map map = new HashMap();
       map.put(ConstValue.SUCCESS, success);
       map.put(ConstValue.CODE, code);
       map.put(ConstValue.DATA, value);
       HttpServletResponse response = getResponse();
       response.setContentType("text/html;charset=UTF-8");
       response.setCharacterEncoding("UTF-8");
       try {
           String jsonString = JSON.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect);
           //System.out.println(jsonString);
           response.getWriter().write(jsonString);
       } catch (IOException e) {
           e.printStackTrace();
       }
    }
    
    //检查令牌
    public String checkToken(String token) {
        //从redis中根据token获取用户id
        String parseId = "";
        Jedis jedis = null;
        try {
            jedis = JedisUtils.getJedis();
        } catch (Exception e) {
            e.printStackTrace();
            throw new KumaoException("服务器这边好像出了点问题");
        }
        try {
            parseId = JWTUtils.parseJWT(token);
        } catch (Exception e1) {
            e1.printStackTrace();
            throw new KumaoException("访问令牌有误");
        }
        String userId = jedis.hget(ConstValue.SERVER_TOKEN, parseId);
        if(userId == null || userId.trim().length() <= 0 || !parseId.equals(userId)) {
            throw new KumaoException("访问令牌无效");
        }
        JedisUtils.closeJedis(jedis);
        return userId;
    }
    
    public HttpServletRequest getRequest() throws Exception{
        HttpServletRequest request = ServletActionContext.getRequest();
        request.setCharacterEncoding("UTF-8");
        return request;
    }
    public HttpServletResponse getResponse() {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        return response;
    }
}
